package com.nuliji.util.swagger;

/**
 * Created by GaoJie on 2017/10/31.
 */

import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.*;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.ServletContext;
import static com.google.common.base.Predicates.*;
import static springfox.documentation.builders.PathSelectors.*;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createFrontendApi(ServletContext servletContext) {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("1.frontend")
                .apiInfo(apiFrontendInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.nuliji.controller"))
                .paths(webPath())
                .build()
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true);
    }
    @Bean
    public Docket createBackendApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("2.backend")
                .apiInfo(apiBackendInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.nuliji.controller"))
                .paths(adminPath())
                .build()
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true);
    }

    private Predicate<String> adminPath() {
        return or(
                regex("/admin.*"),
                regex("/common.*")
        );
    }

    private Predicate<String> webPath() {
        return new Predicate<String>() {
            @Override
            public boolean apply(String input) {
                return !input.contains("admin");
            }
        };
    }

    private ApiInfo apiFrontendInfo() {
        return new ApiInfoBuilder()
                .title("前端API")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }

    private ApiInfo apiBackendInfo() {
        return new ApiInfoBuilder()
                .title("管理端API")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}